<?php
/**
 * Created by PhpStorm.
 * User: wwj
 * Date: 2020/9/15
 * Time: 9:36
 * Note: game.php
 */

namespace api;

use app\lib\base;
use app\lib\model\cate;
use app\lib\model\game_cate;
use app\lib\model\settings;

class game extends base
{
    public function test()
    {
        $content    = file_get_contents('game.txt');
        $arr        = explode('********', $content);
        $cate_model = cate::new();
        $model      = \app\lib\model\game::new();
        foreach ($arr as $part) {
            $list = explode(PHP_EOL, trim($part));
            $cate_model->save(['title' => $list[0]]);
            $cate_id = $cate_model->getLastInsertId();
            foreach ($list as $k => $game) {
                if ($k == 0) {
                    continue;
                }
                $model->save(['title' => trim($game), 'cate_id' => $cate_id]);
            }
        }
    }

    /**
     * 游戏列表
     *
     * @param string $keyword
     *
     * @return array
     */
    public function get_list(string $keyword = '')
    {
        $model      = \app\lib\model\game::new();
        $cate_model = cate::new();
        $cate_list  = $cate_model->order(['sort' => 'desc'])->read_all('cate_id,title');
        foreach ($cate_list as $k=>&$cate) {
            if ($keyword) {
                $model->where(['title', 'like', '%' . $keyword . '%']);
            }
            $game_list         = $model->where(['cate_id', $cate['cate_id']])->read_all('game_id,title,`desc`');
            if(empty($game_list)){
                unset($cate_list[$k]);
                continue;
            }
            $cate['game_list'] = $game_list;
        }
        return array_values($cate_list);
    }

    public function get_text()
    {
        $model = settings::new();
        return $model->read_all('type,text');
    }
}